<template>
  <div class="outfits-container">
    <!-- 页面头部 -->
    <div class="page-header"><span class="page-title">我的搭配</span></div>

    <!-- 场景列表 -->
    <div class="occasions-section">
      <div class="occasions-grid">
        <div
          v-for="occasion in occasions"
          :key="occasion"
          :class="{ selected: occasion === selectedOccasion }"
          @click="selectedOccasion = occasion"
        >
          <img
            :src="`/src/assets/icons/${
              occasionIcons[occasions.indexOf(occasion)]
            }`"
            alt=""
            class="icon-img"
          />
          <span>{{ occasion }}</span>
        </div>
      </div>
    </div>

    <!-- 搭配列表 -->
    <div class="outfits-list-container" @scroll="handleScroll">
      <div v-if="listLoading" class="loading-container">
        <van-loading type="spinner" color="#6c63ff" size="48px" />
      </div>
      <template v-else>
        <div v-if="myOutfits.length > 0" class="outfits-list">
          <!-- 搭配创建卡片 -->
          <OutfitCreationCard
            :outfit-preview-image="outfit.finalOutfitImage"
            :outfit-id="outfit._id"
            :photoUrl="outfit.outfitPhoto"
            @photo-upload="handlePhotoUpload"
            @delete="handleDeleteClick"
            v-for="outfit in myOutfits"
            :key="outfit._id"
          />

          <!-- 加载中状态 -->
          <div v-if="loading.value" class="loading-indicator">加载中...</div>

          <!-- 加载完成状态 -->
          <div
            v-if="finished.value && myOutfits.length > 0"
            class="finished-indicator"
          >
            没有更多数据了
          </div>
        </div>
        <div v-if="myOutfits.length == 0" class="empty-state">
          <span>这里还是空的</span>
          <button @click="handleDiyOutfit">创建搭配</button>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { useOutfitStore } from "../store/outfit";
import OutfitCreationCard from "../components/OutfitCreationCard.vue";
import { showToast } from "vant";

const router = useRouter();
const outfitStore = useOutfitStore();

// 从store获取我的搭配数据
const myOutfits = computed(() => outfitStore.outfitsList);
const listLoading = computed(() => outfitStore.loading);

// 场合数据
const occasions = ["全部", "工作", "休闲", "运动", "旅行", "约会", "派对"];

// 场合icon
const occasionIcons = [
  "all.svg",
  "work.svg",
  "coffee.svg",
  "dumbbell.svg",
  "travel.svg",
  "dating.svg",
  "party.svg",
];

// 选中的场合
const selectedOccasion = ref("全部");

// 加载状态管理
const loading = ref(false);
const finished = ref(false);
const error = ref(false);

// 加载搭配数据 - 定义在所有调用之前
const loadOutfits = async () => {
  // 设置加载状态
  loading.value = true;
  error.value = false;

  try {
    // 记录加载前的列表长度
    const prevLength = myOutfits.value.length;

    // 调用store中的方法获取数据
    // fetchOutfitsList方法会自动更新store中的outfitsList
    const result = await outfitStore.fetchOutfitsList();

    // 处理返回的数据格式
    const outfitsToAdd = result.outfitsList || result.items || [];
    const total =
      result.total || result.totalCount || outfitStore.pagination.total;

    // 更新store中的total值
    outfitStore.pagination.total = total;

    // 重要修改：在初始加载时不要轻易设置finished为true
    const pageSize = outfitStore.pagination.pageSize || 10;

    // 只有当确实没有更多数据时才设置finished为true
    // 1. 对于第一页加载，不自动设置finished，除非明确没有数据或数据量很少
    // 2. 对于后续页面，当加载的数据量小于pageSize时才设置finished
    if (
      outfitStore.pagination.currentPage > 1 &&
      outfitsToAdd.length < pageSize
    ) {
      finished.value = true;
    } else if (total > 0 && prevLength + outfitsToAdd.length >= total) {
      finished.value = true;
    } else if (outfitsToAdd.length === 0) {
      finished.value = true;
    } else {
      // 关键：保持finished为false，允许继续滚动加载
      finished.value = false;
    }
  } catch (err) {
    // 设置错误状态
    error.value = true;
    // 显示错误提示
    showToast({
      message: "数据加载失败，请重试",
      position: "bottom",
    });
  } finally {
    // 无论成功失败，都要重置加载状态
    loading.value = false;
  }
};

// 页面挂载时加载数据
onMounted(async () => {
  // 重置分页状态
  outfitStore.pagination.currentPage = 1;
  outfitStore.pagination.totalCount = 0;
  // 重置加载完成状态
  finished.value = false;

  // 加载我的搭配数据
  // await loadOutfits();
});

// 监听场合变化，重新加载数据
watch(
  () => selectedOccasion.value,
  async (newOccasion) => {
    // 重置分页状态
    outfitStore.pagination.currentPage = 1;
    outfitStore.pagination.totalCount = 0;
    // 重置加载完成状态
    finished.value = false;

    // 手动清空outfitsList，确保切换筛选条件时数据正确重置
    outfitStore.outfitsList = [];

    // 设置筛选条件，确保参数格式与后端控制器完全匹配
    const occasion = newOccasion === "全部" ? "" : newOccasion;
    outfitStore.setFilters({ occasion });

    // console.log(`选择场合: ${newOccasion}，实际传递参数: ${occasion || "无"}`);

    // 重新加载数据
    await loadOutfits();
  },
  { immediate: true }
);

// 处理滚动事件
const handleScroll = (event) => {
  // 获取滚动容器
  const container = event.target;

  // 计算滚动位置
  const { scrollTop, scrollHeight, clientHeight } = container;

  // 计算剩余高度和滚动百分比
  const remainingHeight = scrollHeight - clientHeight - scrollTop;

  // 滚动到底部检测逻辑
  const shouldTriggerLoad =
    scrollHeight > clientHeight &&
    !loading.value &&
    !finished.value &&
    remainingHeight < 100;

  if (shouldTriggerLoad) {
    onLoad();
  }
};

// 加载更多数据
const onLoad = async () => {
  // 防止重复加载和无效加载
  if (loading.value || finished.value) {
    return;
  }

  try {
    // 增加页码
    outfitStore.pagination.currentPage++;

    // 调用加载函数
    await loadOutfits();
  } catch (err) {
    // 加载失败时回滚页码，避免页码错乱
    outfitStore.pagination.currentPage = Math.max(
      1,
      outfitStore.pagination.currentPage - 1
    );
  }
};

// 处理删除点击事件
const handleDeleteClick = async (outfitId) => {
  try {
    // 调用删除接口
    await outfitStore.deleteOutfit(outfitId);

    // 删除成功后，重置状态并刷新数据
    showToast({
      message: "删除成功",
      position: "bottom",
    });

    // 重置状态
    outfitStore.pagination.currentPage = 1;
    outfitStore.outfitsList = [];

    // 重新加载数据
    await loadOutfits();
  } catch (error) {
    console.error("删除搭配失败:", error);
    showToast({
      message: "删除失败，请重试",
      position: "bottom",
    });
  }
};

// 处理照片上传
const handlePhotoUpload = async (id, file) => {
  // 基本参数验证
  if (!id || !file) {
    showToast({
      message: "搭配ID或文件不存在",
      position: "bottom",
    });
    return;
  }

  // 对图片进行处理 - 文件格式和大小限制
  if (
    file.type !== "image/jpeg" &&
    file.type !== "image/png" &&
    file.type !== "image/webp"
  ) {
    showToast({
      message: "请上传JPEG、PNG或WebP格式的图片",
      position: "bottom",
    });
    return;
  }

  if (file.size > 10 * 1024 * 1024) {
    showToast({
      message: "图片大小不能超过10MB",
      position: "bottom",
    });
    return;
  }

  try {
    let dataURL;

    // 对于大图片（超过2MB）进行压缩处理
    if (file.size > 2 * 1024 * 1024) {
      dataURL = await compressImage(file);
    } else {
      // 小图片直接转换为data URL
      dataURL = await new Promise((resolve, reject) => {
        const reader = new FileReader();

        // 添加进度事件监听（可选，用于大文件）
        reader.onprogress = (event) => {
          if (event.lengthComputable) {
            const percentLoaded = Math.round(
              (event.loaded / event.total) * 100
            );
          }
        };

        reader.readAsDataURL(file);

        reader.onload = () => {
          try {
            if (!reader.result || typeof reader.result !== "string") {
              throw new Error("图片数据格式错误");
            }
            resolve(reader.result);
          } catch (error) {
            reject(new Error("图片转换失败: " + error.message));
          }
        };

        reader.onerror = (error) => {
          console.error("文件读取错误:", error);
          reject(new Error("图片读取失败"));
        };

        // 添加超时处理
        const timeoutId = setTimeout(() => {
          reader.abort();
          reject(new Error("图片读取超时"));
        }, 30000); // 30秒超时

        reader.onabort = () => {
          clearTimeout(timeoutId);
          reject(new Error("图片读取已中止"));
        };
      });
    }

    // 构建更新数据，只包含需要更新的字段
    const updateData = {
      outfitPhoto: dataURL,
      // 如果需要同时更新finalOutfitImage，可以取消注释下面这行
      // finalOutfitImage: dataURL
    };

    // 调用updateOutfit接口更新搭配数据
    const updatedOutfit = await outfitStore.updateOutfit(id, updateData);

    // 重置分页状态，确保新数据显示在第一页
    outfitStore.pagination.currentPage = 1;
    outfitStore.pagination.totalCount = 0;

    // 手动清空outfitsList，确保数据正确重置
    outfitStore.outfitsList = [];

    // 重新加载数据，应用当前的筛选条件（包括场合筛选）
    await loadOutfits();

    // 显示上传成功提示
    showToast({
      message: "上传成功",
      position: "bottom",
    });
  } catch (error) {
    console.error("处理图片或更新搭配时出错:", error);

    // 根据错误类型提供更具体的错误信息
    let errorMessage = "操作失败";
    if (error.message) {
      errorMessage = error.message;
    } else if (error.response) {
      errorMessage =
        error.response.data?.message || `服务器错误: ${error.response.status}`;
    }

    showToast({
      message: errorMessage,
      position: "bottom",
    });

    return null;
  }
};

// 图片压缩函数
const compressImage = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = (event) => {
      const img = new Image();
      img.src = event.target.result;

      img.onload = () => {
        // 创建Canvas元素进行压缩
        const canvas = document.createElement("canvas");
        let width = img.width;
        let height = img.height;

        // 计算压缩后的尺寸，保持宽高比
        const maxDimension = 1920; // 最大尺寸
        if (width > maxDimension || height > maxDimension) {
          const aspectRatio = width / height;
          if (width > height) {
            width = maxDimension;
            height = width / aspectRatio;
          } else {
            height = maxDimension;
            width = height * aspectRatio;
          }
        }

        canvas.width = width;
        canvas.height = height;

        // 在Canvas上绘制压缩后的图片
        const ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);

        // 根据文件类型选择适当的MIME类型
        const mimeType = file.type || "image/jpeg";

        // 压缩质量（0.1-1之间，数字越小压缩率越高）
        let quality = 0.7;
        if (file.size > 5 * 1024 * 1024) {
          quality = 0.5; // 更大的文件使用更低的质量
        }

        try {
          // 直接获取完整的data URL格式
          const dataURL = canvas.toDataURL(mimeType, quality);
          resolve(dataURL);
        } catch (error) {
          console.error("Canvas转换为DataURL失败:", error);
          reject(new Error("图片压缩失败"));
        }
      };

      img.onerror = () => {
        reject(new Error("图片加载失败"));
      };
    };

    reader.onerror = () => {
      reject(new Error("文件读取失败"));
    };
  });
};

const handleDiyOutfit = () => {
  router.push("/outfits/create");
};
</script>

<style scoped>
.outfits-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 0px 0px 70px 0px;
}

/* 加载指示器样式 */
.loading-indicator {
  padding: 20px;
  text-align: center;
  color: #666;
  font-size: 14px;
}

/* 加载完成指示器样式 */
.finished-indicator {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.page-header .page-title {
  font-size: 16px;
  font-weight: bold;
  color: #000000;
}
.page-header {
  background-color: #fff;
  padding: 20px;
  flex-shrink: 0;
}
.empty-state {
  padding: 50px 0 20px 0;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  border-radius: 0 0 12px 12px;
  flex: 1;
}
.empty-state span {
  font-size: 14px;
  color: #999999;
}
.empty-state button {
  font-size: 14px;
  color: #ffffff;
  background-color: #6c63ff;
  border: none;
  cursor: pointer;
  padding: 10px 50px;
  border-radius: 10px;
  transition: background-color 0.3s ease;
}

.empty-state button:hover {
  background-color: rgba(108, 99, 255, 0.1);
}

.occasions-section {
  padding: 0 20px 20px 20px;
  background-color: #fff;
  /* margin-top: 30px; */
  font-size: 14px;
  color: #999999;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
  -ms-overflow-style: none;
  flex-shrink: 0;
}

.occasions-section::-webkit-scrollbar {
  display: none;
}

.occasions-grid {
  display: flex;
  flex-direction: row;
  gap: 15px;
  white-space: nowrap;
}

.occasions-grid > div {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px 15px;
  cursor: pointer;
  color: #999999;
  transition: color 0.3s ease;
  gap: 5px;
}

.occasions-grid > div:first-child {
  padding-left: 0;
}

/* .occasions-grid > div:last-child {
  padding-right: 0;
} */

.occasions-grid > div.selected {
  color: #000000;
}

.occasions-grid > div.selected svg {
  fill: #000000;
}

.occasions-grid span {
  font-size: 12px;
}

.icon-img {
  width: 26px;
  max-width: none;
}

/* Vant List 样式 */
.outfits-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding-bottom: 20px;
}

/* 搭配卡片样式 */
.outfit-card {
  background-color: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.outfit-card:active {
  transform: scale(0.98);
}

.outfit-item {
  display: flex;
  flex-direction: column;
}

.outfit-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.outfit-info {
  padding: 12px;
}

.outfit-description {
  font-size: 14px;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.outfit-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag {
  font-size: 10px;
  padding: 2px 8px;
  background-color: #f0f0f0;
  border-radius: 12px;
  color: #666;
}

/* 空状态样式 */
:deep(.van-empty) {
  margin: 60px 0;
}

:deep(.van-empty__description) {
  font-size: 14px;
  color: #999;
}

/* 加载状态样式 */
:deep(.van-list__loading) {
  padding: 15px 0;
}

:deep(.van-list__finished-text) {
  font-size: 12px;
  color: #999;
  padding: 15px 0;
}

.outfits-list-container {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
  scrollbar-width: 6px;
  -ms-overflow-style: auto;
  overflow: -moz-scrollbars-none;
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.outfits-list-container::-webkit-scrollbar {
  display: none;
}

.outfits-list-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.outfits-list-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.outfits-list-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.loading-container {
  /* 在父盒子水平垂直居中 */
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
